//
//  CYTime.m
//  CaiYun
//
//  Created by 今日信息科技 on 2017/8/14.
//  Copyright © 2017年 今日信息科技. All rights reserved.
//

#import "CCTime.h"
@interface CCTime(){
    dispatch_source_t _timer;
}
@end
@implementation CCTime
- (instancetype)init{
    self = [super init];
    if (self)
    {
        
    }
    return self;
}

- (void)countDown:(int)number time:(void(^)(NSString *time))time complete:(void(^)(void))complete
{
    __block int new_number = number;
    
    //获取全局队列
    dispatch_queue_t global = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    //创建定时器，并将定时器的任务交给全局队列
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, global);
    
    //dispatch_time_t 里面的都是纳秒 创建一个距离现在多少秒开启的任务
    dispatch_time_t t = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC));

    //设置出发的间隔时间，第三个参数，代表设置定时器触发的时间间隔 1.0s  第四个参数  代表时间允许的误差是 0s
    dispatch_source_set_timer(_timer, t, 1.0 * NSEC_PER_SEC, 0.0000 * NSEC_PER_SEC);
    
    //定时器的触发事件
    dispatch_source_set_event_handler(_timer, ^{
        if (new_number <= 0)
        {
            //关闭定时器
            [self cancel];
            
            if (complete)
                dispatch_async(dispatch_get_main_queue(), ^{
                    complete();//完成回调
                });
        }
        else
            dispatch_async(dispatch_get_main_queue(), ^{
                //将number，转换成时间格式，并且通过主队列，传递出去
                time([NSString stringWithFormat:@"%d",new_number]);
            });
        new_number --;//递减
    });
    dispatch_resume(_timer);
    
}

- (void)cancel{
    if (_timer)//如果定时器存在
        dispatch_source_cancel(_timer);//释放定时器
}

+ (NSString *)timeSince1970
{
    return [NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970]];
}
+ (NSString *)timestamp
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyyMMddhhmmssSSS"];
    return [formatter stringFromDate:[NSDate date]];
}
+ (NSArray *)timeArray{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MM,dd,HH,mm"];//此处不需要用到年，所以去掉yyy
    NSDate *date = [NSDate date];
    NSString *time = [formatter stringFromDate:date];
    return [time componentsSeparatedByString:@","];
}
@end
